package com.company;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @date : 2021/12/8 9:58
 * fastjson转json对象的问题
 */

public class P006_JavaObjectToJSONObject {
    public static void main(String[] args) {
        IdCardInfo info = new IdCardInfo("310101202112081234", "上海市");
        Person person = new Person(null, "张三", 20);
        person.setInfo(info);
        System.out.println(person);
        System.out.println(javaObjectToJSONObject2(person));
        System.out.println(javaObjectToJSONObject(person));
    }

    // 问题代码
    public static JSONObject javaObjectToJSONObject(Person person) {
        String result = JSON.toJSON(person).toString();
        Person resp = JSON.parseObject(result, Person.class);
        return JSON.parseObject(resp.toString());
    }

    // 正常代码
    public static JSONObject javaObjectToJSONObject2(Person person) {
        System.out.println(JSONObject.toJSONString(person));
        return JSON.parseObject(JSON.toJSON(person).toString());
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Person {
        IdCardInfo info;
        String name;
        int age;
    }

    @Data
    @AllArgsConstructor
    public static class IdCardInfo {
        String idNo;
        String address;
    }
}
